package cn.openea.perpartner.common.core.filter;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Weird077
 * @description TODO
 * @date 2022-11-02 15:26
 */
@Slf4j
public class MyHttpServletRequestFilter implements Filter {
    private static final String CONTENT_TYPE = "application/json";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //Do nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (StrUtil.isBlank(request.getContentType()) ||!request.getContentType().toLowerCase().contains(CONTENT_TYPE)){
            chain.doFilter(request, response);
            return;
        }
        if (request instanceof HttpServletRequest) {
            requestWrapper = new MyHttpServletRequestWrapper((HttpServletRequest) request);
        }
        //获取请求中的流，将取出来的字符串，再次转换成流，然后把它放入到新 request对象中
        // 在chain.doFiler方法中传递新的request对象
        if (null == requestWrapper) {
            chain.doFilter(request, response);
            return;
        }
        chain.doFilter(requestWrapper, response);
    }
    @Override
    public void destroy() {
        //Do nothing
    }

}
